import UIKit
import SwiftyJSON
import BXModel
import BXiOSUtils
import Kingfisher
import BXForm
{% set m = model %}
{% if m.has_page %}
    import BXLoadMoreControl
{% endif %}

{% for comment in comments %}
    {{ comment }}
{% endfor %}

class {{ model.class_name }} : {{ model.superclass }} {% if model.has_adapter %}, ListViewController {% endif %} {

{% for field in fields %}
    {{ field.declare_stmt }}
{% endfor %}
{% if not model.no_init %}
{% if model.is_tvc %}
    init(){
    super.init(style:.plain)
    }

    override init(style: UITableViewStyle){
    super.init(style:style)
    }
{% else %}
    convenience init(){
    self.init(nibName: nil, bundle: nil)
    }
{% endif %}
// must needed for iOS 8
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
{% include 'ios/view/uicommon_init.html' %}
{% endif %}

override func loadView(){
    super.loadView()
    self.view.backgroundColor = .background
    {% if not model.no_init %}
    commonInit()
    {% endif %}
}

{%  if model.has_adapter %}
    typealias ModelType = {{ m.ui_model_name }}
    let adapter = SimpleGenericTableViewAdapter<{{ m.ui_model_name }},{{ m.ui_cell_name }}>()
    var modelAdapter: SimpleGenericDataSource<{{ m.ui_model_name }}>{
    return adapter
    }
{%  endif %}

{% if model.has_static_adapter %}
    let staticAdapter = StaticTableViewAdapter()
{% endif %}

{% if m.has_primary_action %}
    var actionCell : PrimaryButtonCell = {
    let cell = PrimaryButtonCell()
    cell.setPrimaryActionTitle("确定")
    cell.primaryButton.setupAsPrimaryActionButton()
    cell.buttonHorizontalInset = 15
    cell.buttonMarginTop = 10
    return cell
    }()
{% endif %}

override func viewDidLoad() {
super.viewDidLoad()
title = ""
navigationItem.title = title
{% if model.has_adapter %}
    {% if  model.adapter_type == 'c' %}
        adapter.bindTo(collectionView)
    {% else %}
        adapter.bindTo(tableView)
    {% endif %}
{% endif %}

{% if model.has_static_adapter %}
    // staticAdapter.append()
    // staticAdapter.appendItems([])
    staticAdapter.bindTo(tableView)
    staticAdapter.didSelectCell = { cell, index in
    self.onTap(cell: cell)
    }
{% endif %}

{% if model.is_tvc %}
    clearsSelectionOnViewWillAppear = true
    tableView.keyboardDismissMode = .onDrag
    tableView.tableFooterView = UIView()
    tableView.rowHeight = 60 // UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 60
    tableView.separatorStyle = .singleLine
    tableView.separatorColor = .seperatorLine

    {% if model.has_search_ui %}
        tableView.tableHeaderView = searchBar
    {% endif %}
{% endif %}
{% if model.has_detail %}
    adapter.didSelectedItem = {
    item,index in
    self.show{{ model.ui_model_name }}Detail(item)
    }
{% endif %}
{% if model.has_req %}
    loadData()
{% endif %}
{% if model.has_refresh %}
    refreshControl = UIRefreshControl(frame: .zero)
    refreshControl?.addTarget(self, action: #selector(onRefresh), for: .valueChanged)
{% endif %}
{% if model.has_page %}
    bx_loadMoreControl = loadMoreControl
    loadMoreControl.onLoadingHandler = {
        self.loadMoreData()
    }
{% endif %}

}

{% if model.has_static_adapter %}
    func onTap(cell:UITableViewCell){
    switch cell{
    default:break
    }
    }
{% endif %}

{% if model.has_tab %}
    var tabType:{{ model.ui_tab_type_name }}!
{% endif %}

{% if model.has_detail %}
    func show{{ model.ui_model_name }}Detail(item:{{ model.ui_model_name }}){
    let vc = {{ model.ui_detail_vc_name }}()
    vc.{{ model.ui_camel_mname }} = item
    show(vc,sender:self)
    }
{% endif %}

{% if model.has_page %}
    var loadMoreControl = BXLoadMoreControl()
{% endif %}

{% if model.has_search %}
{% endif %}
{% if model.has_refresh %}
    func onRefresh(){
        self.refreshData()
    }
{% endif %}
{% if model.has_req %}
    // MARK: Load Data
    func loadData(){
        let params:Params = [:]
        ApiService.listBy(params){ resp in
        self.handle(resp: resp)
        }
    }
{% endif %}

{% if model.has_search_ui %}
    // MARK:Search Support
    var searchBar:UISearchBar = {
    let bar = UISearchBar() //
    bar.showsCancelButton = true
    bar.placeholder = "搜索"
{#    bar.backgroundImage = Asset.#}
    bar.isTranslucent = false
    return bar
    }()
{% endif %}

{% include 'ios/controller/handle_keyboardEvents.html' %}


}

{%  if model.has_search_ui %}
extension {{ model.class_name }}:UISearchBarDelegate{
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let text = searchBar.text , !text.isEmpty{
            search(keyword:text)
        }
    }
}
{% endif %}

{% if m.has_remove %}

    extension {{ m.class_name }} {
    // MARK: Actions
    func remove{{ m.ui_model_name }}(item:{{ m.ui_model_name }}){
    guard let index = adapter.indexOfItem(item) else{
    return
    }
    adapter.removeAtIndex(index)
    let indexPath = NSIndexPath(forRow: index, inSection: 0)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

    // var eventName:String?
    //    NSNotificationCenter.defaultCenter().postNotificationName(dataSetChangedEvent, object: nil)
    }
    }
{% endif %}

{% if model.has_tab %}
    import UIKit
    import BXViewPager

    class {{ model.ui_tab_vc_name }}:BXViewPagerViewController{

    override func viewDidLoad() {
    super.viewDidLoad()
    title = ""
    navigationItem.title = title
    showIndicator = true

    var vcs:[UIViewController] = []
    for type in {{ model.ui_tab_type_name }}.allCases{
    let vc = {{ model.class_name }}()
    vc.tabType = type
    vc.title = type.title
    vcs.append(vc)
    }

    setViewControllers(vcs, animated: true)

    }
    {% if model.has_search %}
        func searchByText(text:String){
        if let vc = currentPageViewController as? {{ model.class_name }}{
        vc.searchByText(text)
        }
        }
    {% endif %}
    }
{% endif %}

{% if model.has_detail %}
    // Stub for detail
    // {{ model.ui_detail_vc_name }}
    // var {{ model.ui_camel_mname }}:{{ model.ui_model_name }}!
{% endif %}
